<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class County extends MY_Controller {
	
	/**
	 * @var CtyUserModel
	 */
	public $mCounty = null;

	public function __construct(){
		parent::__construct();	
		$this->loadModel('CtyUserModel', 'mCounty', 'county');
	}
	
	/**
	 * 首页
	 */
	public function index(){
		
		$this->loadModel('AdmSettingModel', 'mSetting');
		$data = [
				 'status' => $this->adminStatus(),
				 'province' =>$this->mSetting->getLocationByPid(1),
				 'title'=>'区域管理员列表'
		];
		
		$this->view('config/county/home',$data, 'datatable,select2');
	}
	
	/**
	 * 添加管理员
	 */
	public function add(){
		
		if($_POST){
			$this->_save();
		}
		
		$this->loadModel('AdmSettingModel', 'mSet');
		$data = array(
				'province' =>$this->mSet->getLocationByPid(1),
				'is_add' => true,
		);
		$this->view('config/county/save', $data,'validation,select2,uniform');
	}
	
	/**
	 * 编辑
	 */
	public function edit(){
		
		if($_POST){
			$this->_save();
		}
		$this->loadModel('AdmSettingModel', 'mSet');
		$id = get('id');
		if( ! $id || ! is_numeric($id)){
			show_404();
		}
		$tA = $this->mCounty->getInfo(get('id'));
		if ( ! $tA){
			show_404();
		}

		$data = array(
				'province' =>$this->mSet->getLocationByPid(1),
				'is_add' => false,
				'admin'=>$tA,
		);
		
		$this->view('config/county/save', $data, 'validation,select2,uniform');
	}
	
	/**
	 * 保存数据
	 */
	private function _save(){
		
		//表单验证
		$vConf = array(
				array('manager', '管理人员', 'required|max_length[12]'),
				array('section_name', '部门名称', 'required|max_length[20]'),
				array('mobile', '手机号码', 'required|valid_mobile'),
				array('account', '帐号', 'required|max_length[15]'),
				array('status', '状态', 'required|in_list[1,2]'),
				array('password', '密码', 'max_length[15]|min_length[6]'),
		);
		$this->formDataValidation($vConf);
		
		$id = post('id');
		if($id && ! is_numeric($id)){
			$this->ajaxReturn(0, '参数错误');	
		}
		
		if($id){
			$info = $this->mCounty->getInfo($id);
			if( ! $info){
				$this->ajaxReturn(0, '信息不存在');	
			}
		}
		
		$data = [
				 'account' => trim(post('account')),
				 'section_name' => trim(post('section_name')),
				 'mobile' => trim(post('mobile')),
				 'manager' => trim(post('manager')),
				 'status' => post('status'),
				 'updatetime' => time()
		];
		
		if($this->mCounty->accountIsExist($data['account'], $id)){
			$this->ajaxReturn(0, '账号已经存在');
		}
		
		$password = post('password');
		if( ! $id && ! $password){
			$this->ajaxReturn(0, '密码不能为空');
		}
		
		if($password){
			$data['password'] = setPassword($password);
		}
		
		//数据保存
		$this->db->trans_begin();
		if( ! $id){
			$data['addtime'] = time();
			if( ! ($id = $this->mCounty->insert($this->mCounty->tbCounty, $data))){
				$this->db->trans_rollback();
				$this->ajaxReturn(0, '保存失败');	
			}
		}else{
			$this->db->where('id', $id);
			if( ! $this->mCounty->update($this->mCounty->tbCounty, $data)){
				$this->db->trans_rollback();
				$this->ajaxReturn(0, '保存失败');
			}
		}
		
		//验证区域数据
		$province = post('province');
		$city = post('city');
		$county = post('county');
		
		if( ! $province){
			$this->db->trans_rollback();
			$this->ajaxReturn(0, '区域必须填写');
		}
		
		if( ! is_array($province)){
			$this->db->trans_rollback();
			$this->ajaxReturn(0, '参数错误');
		}
		
		$item = [];
		foreach ($province as $k => $v){
				
			if( ! is_numeric($v)){
				$this->db->trans_rollback();
				$this->ajaxReturn(0, '参数错误');
			}
				
			if( ! isset($city[$k]) || ! is_numeric($city[$k])){
				$this->db->trans_rollback();
				$this->ajaxReturn(0, '参数错误');
			}
				
			if( ! isset($county[$k]) || ! is_array($county[$k]) || count($county[$k]) == 0){
				$this->db->trans_rollback();
				$this->ajaxReturn(0, '参数错误');
			}
				
			foreach ($county[$k] as $vv){
				if( ! is_numeric($vv)){
					$this->db->trans_rollback();
					$this->ajaxReturn(0, '参数错误');
				}
				$item[] = [
							'province_id' => $v,
						    'city_id' => $city[$k],
							'county_id' => $vv,
							'admin_id' => $id
				];
			}
		}
		
		$this->db->where('admin_id', $id);
		if( ! $this->mCounty->delete($this->mCounty->tbCountyItem)){
			$this->db->trans_rollback();
			$this->ajaxReturn(0, '保存失败');
		}
		
		if( ! $this->mCounty->insertBatch($this->mCounty->tbCountyItem, $item)){
			$this->db->trans_rollback();
			$this->ajaxReturn(0, '保存失败');
		}
		
		$this->db->trans_commit();
		$this->ajaxReturn(1,'保存成功','',getUrl('config/county'));
	}
	
	/**
	 * 列表
	 */
	public function getList(){
		
		$manager = trim(get('manager'));
		$account = trim(get('account'));
		$sectionName = trim(get('section_name'));
		$status = (int)get('status');
		$province = (int)get('province');
		$city = (int)get('city');
		$county = get('county');
		
		$this->db->select('id,account,section_name,manager,mobile,status,addtime')
				 ->order_by('id desc');
		
		if($manager){
			$this->db->like('manager', $manager);
		}
		
		if($account){
			$this->db->like('account', $account);
		}
		
		if($sectionName){
			$this->db->like('section_name', $sectionName);
		}
		
		if($status){
			$this->db->where('status', $status);
		}
		
		if($county && is_array($county)){
			foreach ($county as $k => $v){
				if( ! $v) unset($county[$k]);
			}
		}
		
		$table = $this->mCounty->tbCounty.' a';
		if($province || ($county && is_array($county)) || $city){
			
			$table = '(select 
						c.id,c.account,c.section_name,c.manager,c.mobile,c.status,c.addtime
					from
						'.$this->mCounty->tbCounty.' c
					join
						'.$this->mCounty->tbCountyItem.' i on c.id = i.admin_id where ';
			
			$where = '';
			if($province > 0){
				$where = 'i.province_id = '.$province;
			}
			
			if($city > 0){
				if($where){
					$where .= ' and i.city_id = '.$city;
				}else{
					$where = 'i.city_id = '.$city;
				}
			}
			
			if($county){
				if($where){
					$where .= ' and i.county_id in ('.implode(',', $county).')';
				}else{
					$where = ' i.county_id in ('.implode(',', $county).')';
				}
			}
			
			$table .= $where.' group by c.id)a';
		}
		
		$data = $this->mCounty->pagination($table, null, 'a.id');
		if ($data['data']){
			
			$id = [];
			foreach ($data['data'] as $v){
				$id[] = $v['id'];
			}
			
			$items = $this->mCounty->getCountyItem($id);
			
			foreach ($data['data'] as $k => $v){
				$data['aaData'][$k][] = $v['manager'];
				$data['aaData'][$k][] = $v['account'];
				$data['aaData'][$k][] = $v['mobile'];
				$data['aaData'][$k][] = $v['section_name'];
				
				$tS = '';
				if(isset($items[$v['id']])){
					foreach ($items[$v['id']] as $vv){
						if( ! $tS){
							$tS = $vv['province'].'-'.$vv['city'].'-'.$vv['county'];
						}else{
							$tS .= '，'.$vv['province'].'-'.$vv['city'].'-'.$vv['county'];
						}						
					}
				}
				
				$data['aaData'][$k][] = $tS;
				$data['aaData'][$k][] = date('Y-m-d',$v['addtime']);
                $status = $v['status'] == 1 ? 2 : 1;
				$data['aaData'][$k][] = adminCreateBtn(array(
                    'label' => $this->adminStatus($v['status'], true),
                    'attr' => array(
                        'href' => getUrl('config/county/changeStatus?id='.$v['id']),
                        'alert-message' => "确认是否".$this->adminStatus($status)."？",
                        'class' => 'ajax-request-btn deco',
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'classes',
                        'key' => 'edit'
                    )
                ));

				$data['aaData'][$k][] = adminCreateBtn(array(
                    'label' => '编辑',
                    'attr' => array(
                        'href' => getUrl('config/county/edit?id='.$v['id']),
                        'class' => 'btn btn-xs blue-stripe default'
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'classes',
                        'key' => 'edit'
                    )
                ));
			}
		}
		unset($data['data']);
		echo json_encode($data);
	}
	
	/**
	 * 获取区域列表
	 */
	public function getAreaByPid(){
		
		$this->loadModel('AdmSettingModel', 'mSetting');
		$pid = (int)get('pid');
		$tA = $this->mSetting->getLocationByPid($pid);
		$data = [];
		foreach ($tA as $v){
			$data[] = [
						'id' => $v['id'],
						'name' => $v['name']
			];
		}
		
		$this->ajaxReturn(1, '', $data);
	}

	/**
     * 修改状态
     * @author heyu
     */
	public function changeStatus(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));
        $id = (int)get('id');
        $info = $this->mCounty->getInfo($id, true);
        if (!$info){
            $this->ajaxReturn(0, '管理员不存在');
        }
        $status = $info['status'] == 1 ? 2 : 1;
        $this->db->where(array('id' => $id));
        $tA = $this->mCounty->update($this->mCounty->tbCounty, array('status' => $status));
        if (!$tA){
            $this->ajaxReturn(0, '保存失败');
        }
        $this->ajaxReturn(1, '保存成功');
    }
}
